import React from 'react'
import { withRouter, Link } from 'react-router-dom'
import { Form, Input, Button, Checkbox } from 'antd'
import { UserOutlined, LockOutlined, EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons'
import { useDispatch } from "redux-react-hook"
import * as userApi from '@/api/user'
import { iframeRoutes } from '@/router/routerConfig'
import { saveToken, saveUserInfo, saveRoutes } from '@/redux/actions/user'

const Login = (props) => {
  const dispatch = useDispatch()
  const onLogin = async (formData) => {
    const { data } = await userApi.login(formData)
    dispatch(saveToken(data.token))
  }
  const getUserInfo = async () => {
    const { data } = await userApi.getInfo()
    dispatch(saveUserInfo(data))
  }
  // 将路由数据设置到仓库中，进行状态管理
  const getMenuList = async () => {
    dispatch(saveRoutes(iframeRoutes))
  }
  const onFinish = async (values) => {
    await onLogin(values)
    await getUserInfo()
    await getMenuList()
    props.history.push('/')
  }

  return (
    <Form
      name="normal_login"
      className="login-form"
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
      style={{ margin: '15vh auto 0', width: '300px' }}
    >
      <Form.Item
        name="username"
        rules={[
          {
            required: true,
            message: '请输入用户名!',
          },
        ]}
      >
        <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="用户名: admin" />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[
          {
            required: true,
            message: '请输入密码!',
          },
        ]}
      >
        <Input.Password
          prefix={<LockOutlined className="site-form-item-icon" />}
          iconRender={visible => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
          placeholder="密码: password"
        />
      </Form.Item>
      <Form.Item>
        <Form.Item name="remember" valuePropName="checked" noStyle>
          <Checkbox>自动登录</Checkbox>
        </Form.Item>
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" block className="login-form-button">
          登录
        </Button>
        <div>
          <Link className="login-form-forgot" to="/">找回密码 </Link>
          <Link className="login-form-register" to="/">立即注册</Link>
        </div>
      </Form.Item>
    </Form>
  );
};

export default withRouter(Login)